package com.huawei.M01.iterator;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class Sum01 {
    public static void main(String[] args) {

    }

    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> resultSet = new ArrayList<>();
        // 2. 排序
        Arrays.sort(nums);
        if (nums.length < 3 || nums[0] > 0 || nums[nums.length - 1] < 0) {
            return new ArrayList<>();
        }
        // 3. 三指针查找
        for (int i = 0; i < nums.length - 2 && nums[i] <= 0; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            int j = i + 1;
            int k = nums.length - 1;
            while (j < k) {
                if (nums[i] + nums[j] + nums[k] == 0) {
                    while (j + 1 < k && nums[j] == nums[j + 1]) {
                        j++;
                    }
                    while (k - 1 > j && nums[k] == nums[k - 1]) {
                        k--;
                    }
                    List<Integer> helpList = new ArrayList<>();
                    helpList.add(nums[i]);
                    helpList.add(nums[j]);
                    helpList.add(nums[k]);
                    resultSet.add(helpList);
                    j++;
                    k--;
                } else if (nums[i] + nums[j] + nums[k] < 0) {
                    j++;
                } else {
                    k--;
                }
            }
        }
        return resultSet;
    }
}
